import 'package:get/get.dart';
import 'package:speed_random/common/common_fuc.dart';
import 'package:speed_random/pages/home/rand_num/logic.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert'; // 引入 json 相关库

import 'state.dart';

class RandListLogic extends GetxController {
  final RandListState state = RandListState();
  var cachekey = '';
  @override
  void onInit() {
    super.onInit();
    initCache();
    cachekey=state.randComArgs.value.cachekey;
  }

  // 初始化缓存
  Future<void> initCache() async {
    final prefs = await SharedPreferences.getInstance();

    // 读取历史记录
    final String? historyJson = prefs.getString(cachekey+'historyNumbers');
    if (historyJson != null) {
      try {
        state.historyNumbers.value = jsonDecode(historyJson);

      } catch (e) {
        addCustomList(-2,title: "Here is a list of examples".tr,list: "Emily,James,Sophia,Benjamin,Olivia");
        /*state.historyNumbers.value =[{
          'title': "这是一个例子的列表".tr,
          'list': "Emily,James,Sophia,Benjamin,Olivia",
          'id':commonFuc.generateDeviceId(number: 10),
        }];*/
        print('解析历史记录失败(使用默认值): $e');
      }
    }else{
      addCustomList(-2,title: "Here is a list of examples".tr,list: "Emily,James,Sophia,Benjamin,Olivia");
    }
  }


  Future<void> addCustomList(index,{String title="",list=""}) async {
    final prefs = await SharedPreferences.getInstance();
    final String? historyJson = prefs.getString(cachekey+'historyNumbers');
    state.historyNumbers.value = historyJson != null ? jsonDecode(historyJson) : [];
    print(state.historyNumbers.value);
    print(index);
    if (index!=null && index >-1) {
      if (list!="") {
        state.historyNumbers.value[index]["list"] = list;
      }
      if (title!="") {
        state.historyNumbers.value[index]["title"] = title;
      }
    }else{
      state.historyNumbers.add({
        'title': title,
        'list': list,
        'id':commonFuc.getRandomId(number: 10),
      });
    }
    await prefs.setString(cachekey+'historyNumbers', jsonEncode(state.historyNumbers.value));
  }
  Future<void> removeCustomList(index) async {
    final prefs = await SharedPreferences.getInstance();
    final String? historyJson = prefs.getString(cachekey + 'historyNumbers');
    state.historyNumbers.value =
    historyJson != null ? jsonDecode(historyJson) : [];
    if (index != null && index > -1) {
      state.historyNumbers.value.removeAt(index);
    }
    await prefs.setString(
        cachekey + 'historyNumbers', jsonEncode(state.historyNumbers.value));
  }
  // 清空历史记录
  Future<void> clearHistory() async {
    state.historyNumbers.clear();
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(cachekey+'historyNumbers');
    await prefs.remove(cachekey+'randomNumbers');
    await prefs.remove(cachekey+'randomNumbersSum');
    final RandNumLogic logic = Get.put(RandNumLogic());
    final  statenum =Get.find<RandNumLogic>().state;
    statenum.historyNumbers.value = [];
    statenum.randomNumbers.value = [];
    statenum.randomNumbersSum.value = 0;
    update();
  }


}
